<template>
  <div class="cms-articles-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>文章管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            发布文章
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="文章标题">
            <el-input 
              v-model="searchForm.title" 
              placeholder="请输入文章标题"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="栏目">
            <el-select 
              v-model="searchForm.categoryId" 
              placeholder="请选择栏目"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option 
                v-for="cat in categories" 
                :key="cat.id" 
                :label="cat.name" 
                :value="cat.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="全部" value="" />
              <el-option label="已发布" value="published" />
              <el-option label="草稿" value="draft" />
              <el-option label="待审核" value="pending" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量操作 -->
      <div class="toolbar">
        <el-button 
          type="danger" 
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出文章
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="文章标题" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="article-title">
              <el-tag v-if="row.isTop" type="danger" size="small" effect="dark" style="margin-right: 5px">
                置顶
              </el-tag>
              <el-tag v-if="row.isHot" type="warning" size="small" style="margin-right: 5px">
                热门
              </el-tag>
              <el-tag v-if="row.isRecommend" type="success" size="small" style="margin-right: 5px">
                推荐
              </el-tag>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="栏目" width="120" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.category }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="100" align="center" />
        <el-table-column prop="views" label="浏览量" width="100" align="center" sortable>
          <template #default="{ row }">
            <el-text type="primary">{{ row.views }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="comments" label="评论数" width="100" align="center" sortable>
          <template #default="{ row }">
            <el-text type="success">{{ row.comments }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)"
              effect="plain"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" sortable />
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'published'"
              type="warning" 
              size="small" 
              link
              @click="handleUnpublish(row)"
            >
              <el-icon><CircleClose /></el-icon>
              下线
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑文章抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      size="70%"
      :close-on-click-modal="false"
      @close="handleDrawerClose"
      direction="rtl"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
        class="article-form"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input 
                v-model="form.author" 
                placeholder="请输入作者"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属栏目" prop="categoryId">
              <el-select 
                v-model="form.categoryId" 
                placeholder="请选择栏目"
                style="width: 100%"
              >
                <el-option 
                  v-for="cat in categories" 
                  :key="cat.id" 
                  :label="cat.name" 
                  :value="cat.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="标签">
          <el-select 
            v-model="form.tags" 
            multiple
            placeholder="请选择标签"
            style="width: 100%"
          >
            <el-option 
              v-for="tag in tags" 
              :key="tag.id" 
              :label="tag.name" 
              :value="tag.id" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封面图片">
          <el-upload
            class="cover-uploader"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            action="#"
            :auto-upload="false"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="cover-image" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div style="margin-top: 5px;">
            <el-text size="small" type="info">建议尺寸：800x450像素</el-text>
          </div>
        </el-form-item>

        <el-form-item label="文章摘要" prop="summary">
          <el-input 
            v-model="form.summary" 
            type="textarea"
            :rows="3"
            placeholder="请输入文章摘要"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="文章内容" prop="content" class="editor-form-item">
          <div class="rich-editor-wrapper">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
              class="editor-toolbar"
            />
            <Editor
              v-model="form.content"
              :defaultConfig="editorConfig"
              mode="default"
              class="editor-content"
              @onCreated="handleCreated"
              @onChange="handleEditorChange"
            />
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="选择发布时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章属性">
              <el-checkbox v-model="form.isTop">置顶</el-checkbox>
              <el-checkbox v-model="form.isHot">热门</el-checkbox>
              <el-checkbox v-model="form.isRecommend">推荐</el-checkbox>
              <el-checkbox v-model="form.allowComment">允许评论</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>SEO设置</el-divider>

        <el-form-item label="SEO标题">
          <el-input 
            v-model="form.seoTitle" 
            placeholder="留空则使用文章标题"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="SEO关键词">
          <el-input 
            v-model="form.seoKeywords" 
            placeholder="多个关键词用逗号分隔"
          />
        </el-form-item>

        <el-form-item label="SEO描述">
          <el-input 
            v-model="form.seoDescription" 
            type="textarea"
            :rows="2"
            placeholder="留空则使用文章摘要"
            maxlength="160"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button @click="handleSubmit('draft')">
            保存草稿
          </el-button>
          <el-button type="primary" @click="handleSubmit('published')" :loading="submitLoading">
            发布
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, shallowRef, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Search, Refresh, Edit, Delete, Download, View, CircleClose
} from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 栏目列表
const categories = ref([
  { id: 1, name: '公司新闻' },
  { id: 2, name: '行业动态' },
  { id: 3, name: '产品资讯' },
  { id: 4, name: '技术文章' },
  { id: 5, name: '经验分享' }
])

// 标签列表
const tags = ref([
  { id: 1, name: 'ERP' },
  { id: 2, name: '管理' },
  { id: 3, name: '技术' },
  { id: 4, name: '产品' },
  { id: 5, name: '行业' }
])

// 搜索表单
const searchForm = reactive({
  title: '',
  categoryId: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 抽屉
const drawerVisible = ref(false)
const drawerTitle = ref('发布文章')
const formRef = ref()
const submitLoading = ref(false)

// 富文本编辑器
const editorRef = shallowRef()
const toolbarConfig = {
  excludeKeys: []
}
const editorConfig = {
  placeholder: '请输入文章内容...',
  MENU_CONF: {}
}

// 编辑器创建
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 编辑器内容改变
const handleEditorChange = (editor) => {
  // 内容已通过v-model自动同步
}

// 表单数据
const form = reactive({
  id: null,
  title: '',
  categoryId: '',
  tags: [],
  author: '',
  coverImage: '',
  summary: '',
  content: '',
  publishTime: '',
  isTop: false,
  isHot: false,
  isRecommend: false,
  allowComment: true,
  seoTitle: '',
  seoKeywords: '',
  seoDescription: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属栏目', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 状态类型
const getStatusType = (status) => {
  const typeMap = {
    published: 'success',
    draft: 'info',
    pending: 'warning'
  }
  return typeMap[status] || 'info'
}

// 状态文本
const getStatusText = (status) => {
  const textMap = {
    published: '已发布',
    draft: '草稿',
    pending: '待审核'
  }
  return textMap[status] || status
}

// 查询
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.title = ''
  searchForm.categoryId = ''
  searchForm.status = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  drawerTitle.value = '发布文章'
  drawerVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  drawerTitle.value = '编辑文章'
  Object.assign(form, { ...row })
  drawerVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看文章：' + row.title)
  // 实际应跳转到文章详情页
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除文章"${row.title}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 篇文章吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('批量删除成功')
    loadData()
  }).catch(() => {})
}

// 下线文章
const handleUnpublish = (row) => {
  ElMessageBox.confirm(
    `确定要下线文章"${row.title}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('文章已下线')
    loadData()
  }).catch(() => {})
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 提交
const handleSubmit = async (status) => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const action = form.id ? '更新' : '发布'
        const statusText = status === 'published' ? '发布' : '保存草稿'
        ElMessage.success(`${action}成功，文章已${statusText}`)
        
        drawerVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('操作失败：' + error.message)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 封面上传成功
const handleCoverSuccess = (response) => {
  form.coverImage = response.url
  ElMessage.success('封面上传成功')
}

// 抽屉关闭
const handleDrawerClose = () => {
  formRef.value?.resetFields()
  form.id = null
  form.coverImage = ''
  form.tags = []
  form.content = ''
}

// 组件卸载时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
})

// 分页改变
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    tableData.value = [
      {
        id: 1,
        title: '如何高效使用ERP系统提升企业管理效率',
        category: '产品资讯',
        author: '张三',
        views: 1580,
        comments: 23,
        status: 'published',
        publishTime: '2024-10-15 10:30:00',
        isTop: true,
        isHot: true,
        isRecommend: false
      },
      {
        id: 2,
        title: '2024年制造业数字化转型趋势分析',
        category: '行业动态',
        author: '李四',
        views: 892,
        comments: 15,
        status: 'published',
        publishTime: '2024-10-14 14:20:00',
        isTop: false,
        isHot: true,
        isRecommend: true
      },
      {
        id: 3,
        title: '新版本功能介绍：智能预测系统上线',
        category: '公司新闻',
        author: '王五',
        views: 1256,
        comments: 31,
        status: 'published',
        publishTime: '2024-10-13 09:00:00',
        isTop: false,
        isHot: false,
        isRecommend: true
      },
      {
        id: 4,
        title: '从零开始搭建企业CMS系统',
        category: '技术文章',
        author: '赵六',
        views: 524,
        comments: 8,
        status: 'draft',
        publishTime: '',
        isTop: false,
        isHot: false,
        isRecommend: false
      },
      {
        id: 5,
        title: '企业数据安全最佳实践指南',
        category: '经验分享',
        author: '钱七',
        views: 0,
        comments: 0,
        status: 'pending',
        publishTime: '',
        isTop: false,
        isHot: false,
        isRecommend: false
      }
    ]
    
    pagination.total = tableData.value.length
  } catch (error) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cms-articles-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.article-title {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.cover-uploader {
  width: 200px;
  height: 120px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.cover-uploader:hover {
  border-color: var(--el-color-primary);
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-image {
  width: 200px;
  height: 120px;
  object-fit: cover;
  display: block;
}

.editor-container {
  width: 100%;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 富文本编辑器样式 */
.article-form {
  padding-right: 20px;
}

.editor-form-item {
  margin-bottom: 30px;
}

.rich-editor-wrapper {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  border-bottom: 1px solid #ccc;
}

.editor-content {
  height: 400px;
  overflow-y: auto;
}

/* 编辑器内容区域样式 */
:deep(.w-e-text-container) {
  background-color: #fff;
}

:deep(.w-e-text-placeholder) {
  color: #999;
  font-style: normal;
}

/* 抽屉内表单优化 */
.article-form :deep(.el-form-item__label) {
  font-weight: 500;
}

/* 抽屉footer固定底部 */
:deep(.el-drawer__footer) {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  background-color: #fff;
}
</style>

